<?php
//material_search 素材采集
header('Content-Type:text/html;charset=utf8');
require_once __DIR__ . "/../db_orm.php";
require_once __DIR__ . "/../function.php";

use Illuminate\Database\Capsule\Manager as DB;

$db_table1 = 'product';
$db_table2 = 'news';

$res = get_res($db_table1, $db_table2);
//5118配置
$host = "http://apis.5118.com";
$path = "/api/sucai";
$method = "POST";
$apikey = "BF74BDDCF7584279ABE28C0707ECC4D4";
$headers = array();
array_push($headers, "Authorization:" . $apikey);
//根据API的要求，定义相对应的Content-Type
array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
$url = $host . $path;

if (!empty($res)) {
    foreach ($res as $key => $value) {
        $insert_id = DB::table($db_table2)->insertGetId(['keyword' => $value['name'], 'p_id' => 0, 'open' => 1]);

        for ($page_index = 1; $page_index < 1000; $page_index++) {
            $bodys = "keyword=" . $value['name'] . "&page_index=" . $page_index . "&page_size=100";
            while (1) {
                $bodyInfo = curl_post($url, $headers, $bodys);
                $bodyInfo = json_decode($bodyInfo, true);
//                var_dump($bodyInfo['data']['errmsg']);
                if ($bodyInfo['data']['errmsg'] != '数据采集中') {
                    break;
                }
                sleep(1);
            }
//                    var_dump($bodyInfo);exit;
            if ($bodyInfo['data']['errcode'] == 0) {
                //当前页无数据跳出for循环
                if (!empty($bodyInfo['data']['data'])) {
                    $data = $bodyInfo['data']['data'];
                    $insert_data = array();
                    foreach ($data as $k => $v) {
                        $insert_data[$k] = [
                            'p_id' => $insert_id,
                            'keyword' => $value['name'],
                            'open' => 0,
                            'page_index' => $bodyInfo['data']['page_index'],
                            'page_size' => $bodyInfo['data']['page_size'],
                            'total' => $bodyInfo['data']['total'],
                            'guid' => $v['guid'],
                            'title' => $v['title'],
                            'issueTime' => $v['issueTime'],
                            'isOriginal' => $v['isOriginal'],
                            'resourcePlatformName' => $v['resourcePlatformName'],
                            'catalogName' => $v['catalogName'],
                            'url' => $v['url'],
                        ];
                    }
                    DB::table($db_table2)->insert($insert_data);
                } else {
                    break;
                }
            } else {
                echo $bodyInfo['data']['errmsg'] . "\n";
            }
        }
        echo ($key + 1) . "/" . count($res) . "\n";
        sleep(1);
//        if ($key == 50) {
//            break;
//        }
    }
}